<?php

class P4PAction extends AliCommonAction {
	
	public $cmTableName = 'P4P';
	
	
	
	public function _initialize(){
		
		parent::_initialize();
	}
	
	//获取用户后台使用权限/0不通过，1通过，2过期
	public function getAuth(){
		
		
		$username = $_REQUEST['username']; 
		
		$cond = array();
		$cond['username'] = $username;
		
		$userInfo = M('member')->where($cond)->find();
		
		$return  = array();
		$return['status']    = 0;
		$return['member_id'] = 0;
		
		if($userInfo){
			
			$return['status']       = 1;
			
			if( time() < $userInfo['endtime'] ){
				
				
				$return['member_id']    = $userInfo['member_id'];
				
			}else{
				
				$return['status']       = 2;
			}
			
			
		}else{
			
			$return['status']    = 0;
			
			
		}
		
		die(json_encode($return));
	}
	
	//注册用户
	public function registerUser($username){
		
		$where = array();
		$where['username'] = $username;
		
		$count = M('member')->where($where)->count();
		
		if($count>0){
			
			return false;
		}else{
			
			$dataAdd = array();
			$dataAdd['username'] = $username;
			$dataAdd['addtime']  = time();
			$dataAdd['endtime']  = time()+7*24*60*60;
			
			$res = M('member')->add($dataAdd);
			
			if($res){
				
				return $res;
			}else{
				
				return false;
			}
			
		}
	}
	
	
	//批量启动/暂停竞价组
    public function groupBatchStartStop(){
		
		
		$action = $_REQUEST['action'];  
		$username = $_REQUEST['username'];  
		$groups = $_REQUEST['groups'];
		
		if(!empty($groups)){ $groups = explode(DOT,$groups); }
		
		if($action=='start'){
			
			foreach($groups as $val){

				$cond = array();
				$cond['group_id'] = $val;
				
				$data = array();
				$data['status'] = 1;
				
				M('strategy')->where($cond)->save($data);
				
				
			}
			die('1');
		}
		
		if($action=='stop'){
			
			foreach($groups as $val){

				$cond = array();
				$cond['group_id'] = $val;
				
				$data = array();
				$data['status'] = 2;
				
				M('strategy')->where($cond)->save($data);
				//AAA('BBB');
			}
			die('1');
		}
	}
	
	
	//竞价组部分
	
	//竞价组列表 
	public function bidgroupList(){
		
		$username = $_REQUEST['username'];
		
		$member_id = $this->member_id;
		
		$return = array();
		
		
		$list = M('bidgroup')->where('member_id='.$member_id)->order('aligroup_id DESC')->select();
		$count = M('bidgroup')->where('member_id='.$member_id)->count();
		
		foreach($list as $key=>$val){
			
			$nums = M('bidgroup_words')->where('bidgroup_id='.$val['bidgroup_id'].' AND qs_star>2')->count();
			$list[$key]['nums'] = $nums;
		}
		
		$return['list'] 	= $list;
		$return['total'] 	= $count;
		$return['status'] 	= 1;
		
		$this->returnData($return);
		
	}
	
	//添加竞价组
	public function addBidGroup(){
		
		$username 	= empty($_REQUEST['username'])?'':$_REQUEST['username'];
		$title    	= empty($_REQUEST['title'])?'':$_REQUEST['title'];
		
		$return  = array();
		$return['status']    = 0;
		
		$member_id = $this->member_id;
		
		$where = array();
		$where['title'] 	= $title;
		$where['member_id'] = $member_id;
		
		$count  = M('bidgroup')->where($where)->count();
		
		if($count>0){
			
			$return['status']    = -1;
			$return['msg']    	 = '已经存在该竞价组名称！';
			$this->returnData($return);
		}
		
		if(empty($title)){
			
			$return['status']    = -2;
			$return['msg']    	 = '竞价组名称不能为空！';
			$this->returnData($return);
		}
		
		
		$dataAdd = array();
		$dataAdd['member_id'] = $member_id;
		$dataAdd['title']     = $title;
		
		$res = M('bidgroup')->add($dataAdd);
		
		
		
		if($res){
			
			//添加默认竞价方案
			$dataAdd = array();
			$dataAdd['group_id'] 	= 	$res;
			$dataAdd['title'] 		= 	'默认规则';
			$dataAdd['description'] = 	'默认规则作为基础规则，不能删除。在没有设置其他时段的规则时候按照默认规则出价。';
			$dataAdd['member_id'] 	= 	$member_id;
			$dataAdd['is_default']  = 	1;
			$dataAdd['price_speed'] = 	5;
			$dataAdd['top_price']   = 	20;
			$dataAdd['startTime']	=	'00/**/00/**/00';
			$dataAdd['endTime']		=	'23/**/59/**/59';
			$dataAdd['type']		=	1;
			$dataAdd['status']		=	1;
			$dataAdd['price_stept']	=	0.1;
			$dataAdd['fifth_status']=	1;
			
			$res2 = M('strategy')->add($dataAdd);
			
			$return['status']    = 1;
		}else{
			$return['status']    = 0;
			$return['msg']       = '添加竞价组失败！';
		}
		
		$this->returnData($return);
		
	}
	
	//编辑竞价组名称 
	public function editBidGroup(){
		
		$bidgroup_id 	= empty($_REQUEST['bidgroup_id'])? 0: $_REQUEST['bidgroup_id'];
		$title 	        = empty($_REQUEST['title'])? '': $_REQUEST['title'];
		$member_id = $this->member_id;
		
		$return  = array();
		$return['status']    = 0;
		
		$where = array();
		$where['title'] 	= $title;
		$where['member_id'] = $member_id;
		
		$count  = M('bidgroup')->where($where)->count();
		
		if($count>0){
			
			$return['status']    = -1;
			$return['msg']    	 = '已经存在该竞价组名称！';
			$this->returnData($return);
		}
		
		$dataSave = array();
		$dataSave['bidgroup_id'] = $bidgroup_id;
		$dataSave['title']       = $title;
		
		$res = M('bidgroup')->save($dataSave);
		
		
		
		if($res){
			$return['status']    = 1;
		}else{
			$return['status']    = 0;
		}
		$this->returnData($return);
		
	}
	
	//删除竞价组
	public function delBidGroup(){
		
		$bidgroup_id 	= empty($_REQUEST['bidgroup_id'])? 0: $_REQUEST['bidgroup_id'];
		$username 		= empty($_REQUEST['username'])?'':$_REQUEST['username'];
		
		$member_id = $this->member_id;
		
		$res = M('bidgroup')->where('bidgroup_id='.$bidgroup_id.' AND member_id='.$member_id)->delete();
		
		$return  = array();
		$return['status']    = 0;
		
		if($res){
			$return['status']    = 1;
			
			//删除竞价组下的关键词关联记录
			$where = array();
			$where['bidgroup_id'] = $bidgroup_id;
			
			M('bidgroup_words')->where($where)->delete();
		}else{
			$return['status']    = 0;
		}
		$this->returnData($return);
		
	}
	
	//竞价组批量启动，停止
	public function bidGroupBatchStartStop(){
		
		$bidgroup_ids 	= empty($_REQUEST['bidgroup_ids'])? '': $_REQUEST['bidgroup_ids'];
		$action 	    = empty($_REQUEST['action'])? '': $_REQUEST['action'];
		
		$return  = array();
		$return['status']    = 0;
		
		if( empty( $bidgroup_ids ) || empty($action) ){  
		
			$return['status']    = 0;
		}else{
			
			$idsArr = explode(DOT,$bidgroup_ids);
			
			foreach($idsArr as $val){
				
				$dataSave = array();
				$dataSave['bidgroup_id'] = $val;
				
				if($action=='start'){
					$dataSave['bid_status']  = 1;
				}
				if($action=='stop'){
					$dataSave['bid_status']  = 0;
				}
				
				
				M('bidgroup')->save($dataSave);
				
			}
			$return['status']    = 1;
		}
		$this->returnData($return);
		
	}
	
	//添加关键词到关键词组
	public function bidGroupBatchAddWords(){
		
		$action 	    = empty($_REQUEST['action'])? '': $_REQUEST['action'];
		$keyword_ids 	= empty($_REQUEST['keyword_ids'])? '': $_REQUEST['keyword_ids'];
		$bidgroup_id 	= empty($_REQUEST['bidgroup_id'])? 0: $_REQUEST['bidgroup_id'];
		$username 		= empty($_REQUEST['username'])?'':$_REQUEST['username'];
		
		$return  = array();
		$return['status']    = 0;
		
		$keyword_ids = trim($keyword_ids,DOT);
		
		$member_id = $this->member_id;
		
		//AAA($member_id.'ccc');
		if( empty($keyword_ids) || empty($action) ){ 
			
			$return['status']    = 0;
			
			$this->returnData($return);
			
		}
		
		$keywordArr = explode(DOT,$keyword_ids);
		
		$msgStr  = '';
		$flag    = true;
		foreach($keywordArr as $key=>$val){
			
			$keyArr = array();
			$keyArr = explode(DOT2,$val);
			
			$where = array();
			$where['member_id'] 	=  $member_id;
			$where['keyword_id']    =  $keyArr[0];
			
			
			$res = M('bidgroup_words')->where($where)->find();
			
			if($res){
				
				if($msgStr==''){
					
					$msgStr.=$keyArr[1];
				}else{
					$msgStr.=DOT.$keyArr[1];
				}
				$flag = false;
			}
			
		}
		
		if(!$flag){
			
			$return['status']    	 = -1;
			$return['keyWordStr']    = $msgStr;
			$this->returnData($return);
		}
		
		foreach($keywordArr as $val){
			
			$keyArr = array();
			$keyArr = explode(DOT2,$val);
			
			$keyword_id = $keyArr[0];
			
			$dataAdd = array();
			$dataAdd['bidgroup_id'] = $bidgroup_id;
			$dataAdd['keyword_id']  = $keyword_id;
			$dataAdd['member_id']  	= $member_id;
			$dataAdd['keyword']  	= $keyArr[1];
			
			if($action=='add'){
				
				$cond = array();
				$cond['keyword_id']  = $keyword_id;
				$cond['bidgroup_id'] = $bidgroup_id;
				$row = M('bidgroup_words')->where($cond)->find();
				
				if(empty($row)){
					
					M('bidgroup_words')->add($dataAdd);
				}
			}
			if($action=='remove'){
				M('bidgroup_words')->where('keyword_id='.$keyword_id)->delete();
			}
		}
		
		$return['status']    = 1;
		$this->returnData($return);
		
	}
	
	//竞价组中删除关键词
	public function delGroupWords(){
		
		$bidgroup_id 	= empty($_REQUEST['bidgroup_id'])?0:$_REQUEST['bidgroup_id'];
		$username 		= empty($_REQUEST['username'])?'':$_REQUEST['username'];
		$keywordIdStr 	= empty($_REQUEST['keywordIdStr'])?'':$_REQUEST['keywordIdStr'];
		
		$keywordIdArr = explode(DOT,trim($keywordIdStr,DOT));
		
		foreach($keywordIdArr as $val){
			
			$where  = array();
			$where['bidgroup_id']  =  $bidgroup_id;
			$where['keyword_id']   =  $val;
			
			M('bidgroup_words')->where($where)->delete();
		}
		
		$return  = array();
		$return['status']       = 1;
		$this->returnData($return);
	}
	
	//获取某个竞价组下的关键词
	public function getGroupWords(){
		
		$bidgroup_id 	= empty($_REQUEST['bidgroup_id'])?0:$_REQUEST['bidgroup_id'];
		$username 		= empty($_REQUEST['username'])?'':$_REQUEST['username'];
		$pagesize 		= empty($_REQUEST['pagesize'])?10:$_REQUEST['pagesize'];
		$p 				= empty($_REQUEST['p'])?1:$_REQUEST['p'];
		
		$status 	    = empty($_REQUEST['status'])?'':$_REQUEST['status'];
		$qs_star 	    = empty($_REQUEST['qs_star'])?-1:$_REQUEST['qs_star'];
		$keyword 	    = empty($_REQUEST['keyword'])?'':$_REQUEST['keyword'];
		$is_exact 	    = empty($_REQUEST['is_exact'])?'':$_REQUEST['is_exact'];
		
		$sort 	        = empty($_REQUEST['sort'])?'':$_REQUEST['sort'];
		
		$_GET['p'] 		= $p;
		
		$member_id = $this->member_id;
		
		import('ORG.Util.Page');
		
		$where = ' 1 AND member_id='.$member_id;
		
		if(!empty($bidgroup_id)){
			
			$where.= ' AND bidgroup_id='.$bidgroup_id.' ';
		}
		
		
		//$where['qs_star']     = array('gt',2);
		if($qs_star==-1){
			
			
			$where .= ' AND qs_star > 2';
		}else{
			
			$qs_starArr = explode(DOT,trim($qs_star,DOT));
			$tempStr = '';
			
			foreach($qs_starArr as $key=>$val){
				
				if($key==0){
					$tempStr .= 'qs_star='.$val;
				}else{
					
					$tempStr .= ' OR qs_star='.$val;
				}
			}
			
			$tempStr = ' ('.$tempStr.' )';
			
			$where .= ' AND '.$tempStr;
		}
		
		
		
		if(!empty($status)){
			
			$where .= ' AND status= "'.$status.'"';
			//$where['status'] = $status;
		}
		
		if(!empty($keyword)){
			
			if($is_exact=='Y'){
				$where .= ' AND keyword="'.$keyword.'"';
			}else{
				$where .= ' AND keyword like "%'.$keyword.'%"';
			}
			
			
			//$where['keyword'] = array('like','%'.trim($keyword).'%');
		}
		
		$order = '';
		if(!empty($sort)){
			
			$sortArr = explode(DOT,$sort);
			$order   = $sortArr[0].' '.$sortArr[1];
		}
		
		$count      = M('bidgroup_words')->where($where)->count();
		$Page       = new Page($count,$pagesize);
		$show       = $Page->show();
		$lists = M('bidgroup_words')->where($where)->limit($Page->firstRow.','.$Page->listRows)->order($order)->select();
		
		$return  = array();
		$return['status']       = 1;
		$return['pages']     	= $show;
		$return['data']      	= $lists;
		$return['p']      	 	= $p;
		$return['total']     	= $count;
		$return['bidgroup_id']  = $bidgroup_id;
		$this->returnData($return);
		
	}
	
	
	//获取竞价组竞价方案（时段）列表
	
	public function getStrategyList(){
		
		$bidgroup_id 	= empty($_REQUEST['bidgroup_id'])?0:$_REQUEST['bidgroup_id'];
		$username 		= empty($_REQUEST['username'])?'':$_REQUEST['username']; 
		
		$list  = M('strategy')->where('group_id='.$bidgroup_id)->select();
		
		$return  = array();
		$return['status']    = 1;
		$return['data']      = $list;
		$this->returnData($return);
	}
	
	
	//获取某个竞价方案详情
	
	public function getStrategyDetail(){
		
		$strategy_id 	= empty($_REQUEST['strategy_id'])?0:$_REQUEST['strategy_id'];
		
		$res = M('strategy')->where('strategy_id='.$strategy_id)->find();
		
		
		$return  = array();
		$return['status']    = 1;
		$return['data']      = $res;
		$this->returnData($return);
	}
	
	//添加竞价方案（时段）
	public function addStrategy(){
		
		$action 		= empty($_REQUEST['action'])?'':$_REQUEST['action'];
		$username 		= empty($_REQUEST['username'])?'':$_REQUEST['username'];
		
		$strategy_id 	= empty($_REQUEST['strategy_id'])?0:$_REQUEST['strategy_id'];
		$bidgroup_id 	= empty($_REQUEST['bidgroup_id'])?0:$_REQUEST['bidgroup_id'];
		$status 		= empty($_REQUEST['status'])?0:$_REQUEST['status'];
		$title 	        = empty($_REQUEST['title'])?'':$_REQUEST['title'];
		$startTime 	    = empty($_REQUEST['startTime'])?0:$_REQUEST['startTime'];
		$endTime 	    = empty($_REQUEST['endTime'])?0:$_REQUEST['endTime'];
		$description    = empty($_REQUEST['description'])?'':$_REQUEST['description'];
		$type    		= empty($_REQUEST['type'])?'':$_REQUEST['type'];
		
		$first_status   = empty($_REQUEST['first_status'])?0:$_REQUEST['first_status'];
		$second_status  = empty($_REQUEST['second_status'])?0:$_REQUEST['second_status'];
		$third_status   = empty($_REQUEST['third_status'])?0:$_REQUEST['third_status'];
		$fourth_status  = empty($_REQUEST['fourth_status'])?0:$_REQUEST['fourth_status'];
		$fifth_status   = empty($_REQUEST['fifth_status'])?0:$_REQUEST['fifth_status'];
		$sixth_status   = empty($_REQUEST['sixth_status'])?0:$_REQUEST['sixth_status'];
		$seventh_status = empty($_REQUEST['seventh_status'])?0:$_REQUEST['seventh_status'];
		
		$first_price   	= empty($_REQUEST['first_price'])?0:$_REQUEST['first_price'];
		$second_price  	= empty($_REQUEST['second_price'])?0:$_REQUEST['second_price'];
		$third_price   	= empty($_REQUEST['third_price'])?0:$_REQUEST['third_price'];
		$fourth_price  	= empty($_REQUEST['fourth_price'])?0:$_REQUEST['fourth_price'];
		$fifth_price   	= empty($_REQUEST['fifth_price'])?0:$_REQUEST['fifth_price'];
		$seventh_price  = empty($_REQUEST['seventh_price'])?0:$_REQUEST['seventh_price'];
		
		$top_price   	= empty($_REQUEST['top_price'])?20:$_REQUEST['top_price'];
		$price_stept   	= empty($_REQUEST['price_stept'])?0.1:$_REQUEST['price_stept'];
		$price_speed   	= empty($_REQUEST['price_speed'])?5:$_REQUEST['price_speed'];
		
		$isRankFirst   	= empty($_REQUEST['isRankFirst'])?0:$_REQUEST['isRankFirst'];
		$isBasePrice   	= empty($_REQUEST['isBasePrice'])?0:$_REQUEST['isBasePrice'];
		
		$data = array();	
		
		$member_id = $this->member_id;
		
		if($action=='edit'){
			
			$data['title']			=	$title;
			$data['status']			=	$status;
			$data['startTime']		=	$startTime;
			$data['endTime']		=	$endTime;
			$data['description']	=	$description;
			
			
			$data['first_status']	=	$first_status;
			$data['second_status']	=	$second_status;
			$data['third_status']	=	$third_status;
			$data['fourth_status']	=	$fourth_status;
			$data['fifth_status']	=	$fifth_status;
			$data['sixth_status']	=	$sixth_status;
			$data['seventh_status']	=	$seventh_status;
			
			$data['first_price']	=	$first_price;
			$data['second_price']	=	$second_price;
			$data['third_price']	=	$third_price;
			$data['fourth_price']	=	$fourth_price;
			$data['fifth_price']	=	$fifth_price;
			$data['seventh_price']	=	$seventh_price;
			
			$data['top_price']		=	$top_price;
			$data['price_stept']	=	$price_stept;
			$data['strategy_id']	=	$strategy_id;
			$data['price_speed']	=	$price_speed;
			
			$data['isBasePrice']	=	$isBasePrice;
			$data['isRankFirst']	=	$isRankFirst;
			
			$res = M('strategy')->save($data);
		}
		
		if($action=='add'){
			
			$data['title']			=	$title;
			$data['group_id']		=	$bidgroup_id;
			$data['member_id']		=	$member_id;
			$data['is_default']		=	0;
			$data['price_speed']	=	5;
			$data['top_price']		=	20.0;
			$data['fifth_status']	=	1;
			$data['startTime']		=	'00/**/00/**/00';
			$data['endTime']		=	'23/**/59/**/59';
			$data['status']			=	0;
			$data['price_stept']	=	0.1;
			$data['fifth_status']	=	1;
			
			$data['isBasePrice']	=	0;
			$data['isRankFirst']	=	0;
			
			$res = M('strategy')->add($data);
		}
		
		$return  = array();
		$return['status']    = 1;
		
		
		
		if($res){
				
			$return['status']    = 1;	
		}
		
		$this->returnData($return);
	}
	
	public function batchUpdateStrategy(){
		
		$member_id   = $this->member_id;
		$strategys 	= empty($_REQUEST['strategys'])?'':$_REQUEST['strategys'];
		
		if(!empty($strategys)){
			
			$strategys = json_decode($strategys,true);

			//AAA($strategys);
		}
		
		foreach($strategys as $one){
			
			$dataSave = array();
			$dataSave['title']			=	$one['title'];
			$dataSave['status']			=	$one['status'];
			$dataSave['startTime']		=	$one['startTime'];
			$dataSave['endTime']		=	$one['endTime'];
			$dataSave['description']	=	$one['description'];
			
			
			$dataSave['first_status']	=	$one['first_status'];
			$dataSave['second_status']	=	$one['second_status'];
			$dataSave['third_status']	=	$one['third_status'];
			$dataSave['fourth_status']	=	$one['fourth_status'];
			$dataSave['fifth_status']	=	$one['fifth_status'];
			$dataSave['sixth_status']	=	$one['sixth_status'];
			$dataSave['seventh_status']	=	$one['seventh_status'];
			
			$dataSave['first_price']	=	$one['first_price'];
			$dataSave['second_price']	=	$one['second_price'];
			$dataSave['third_price']	=	$one['third_price'];
			$dataSave['fourth_price']	=	$one['fourth_price'];
			$dataSave['fifth_price']	=	$one['fifth_price'];
			$dataSave['seventh_price']	=	$one['seventh_price'];
			
			$dataSave['top_price']		=	$one['top_price'];
			$dataSave['price_stept']	=	$one['price_stept'];
			$dataSave['strategy_id']	=	$one['strategy_id'];
			$dataSave['price_speed']	=	$one['price_speed'];
			
			$dataSave['isBasePrice']	=	$one['isBasePrice'];
			$dataSave['isRankFirst']	=	$one['isRankFirst'];
			
			$res = M('strategy')->save($dataSave);
		}
		
		$return  = array();
		$return['status']    = 1;	
		
		$this->returnData($return);
	}
	
	
	public function deleteStrategy(){
		
		$username 		= empty($_REQUEST['username'])?'':$_REQUEST['username'];
		$strategy_id 	= empty($_REQUEST['strategy_id'])?0:$_REQUEST['strategy_id'];
		
		$member_id 		= $this->member_id;
		
		$where = array();
		$where['strategy_id']  = $strategy_id;
		$where['member_id']    = $member_id;
		
		$res  =  M('strategy')->where($where)->delete();
		
		$return  = array();
		$return['status']    = 0;
		
		if($res){
				
			$return['status']    = 1;	
		}
		
		$this->returnData($return);
	}
	
	//获取当前生效时段 -> 根据时段获取
	public function getNeedUpdatePriceWords(){
		
		$username 		= empty($_REQUEST['username'])?'':$_REQUEST['username'];
		
		$member_id = $this->member_id;
		
		$nowHour   = date('G');
		$nowMinute = date('i');
		$nowSecond = date('s');
		$nowTimeStamp = $nowHour.$nowMinute.$nowSecond;
		
		//获取启动的竞价组  1 为启动
		$where = array();
		$where['status'] 	= 1;
		$where['member_id'] = $member_id;
		$groupList = M('bidgroup')->where($where)->select();
		
		foreach($groupList as $keyGropp=>$group){
			
			$where = array();
			$where['group_id']   = $group['bidgroup_id'];
			$where['status']     = 1;
			
			//获取该组已经启动的时间方案
			$strategyList = array();
			$strategyList = M('strategy')->where($where)->select();
			
			foreach($strategyList as $keyStra=>$strategy){
				
				$timeStartArr   = explode(DOT,$strategy['startTime']);
				$timeStartStamp = $timeStartArr[0].getFullTime($timeStartArr[1]).getFullTime($timeStartArr[2]);
				
				$timeEndArr   = explode(DOT,$strategy['endTime']);
				$timeEndStamp = $timeEndArr[0].getFullTime($timeEndArr[1]).getFullTime($timeEndArr[2]);
				
				if( $nowTimeStamp<=$timeEndStamp && $nowTimeStamp>=$timeStartStamp ){
					
					if( empty($groupList[$keyGropp]['strategy']) ){
						
						$groupList[$keyGropp]['strategy'] = $strategy;
					}else{
						if($strategy['is_default']==0){
							$groupList[$keyGropp]['strategy'] = $strategy;
						}
						
					}
					
				}
				
			}
			
		}
		
		//获取竞价组下所有的关键词
		$allWords 	 = array();
		$where 		 = '1 ';
		
		if(!empty($groupList)){
			
			$tempStr = ' AND ( ';
			
			foreach($groupList as $key=>$group){
				
				if($key==0){
					$tempStr.= ' bidgroup_id='.$group['bidgroup_id'].' ';
				}
				if($key>0){
					$tempStr.= ' OR bidgroup_id='.$group['bidgroup_id'].' ';
				}
				if($key==count($groupList)-1){
					$tempStr.=' ) ';
				}
				
			}
			$where.=$tempStr;
		}
		
		$limit = ' limit 0,1';
		$order = ' ORDER BY last_price_time ASC ';
		$order = ' ';
		$SQL = 'select * from bidgroup_words where '.$where.$order.$limit;
		$allWords = M()->query($SQL);
		
		
		foreach($allWords as $wordKey=>$word){
			
			
			
			foreach($groupList as $group2Key=>$group2){
				
				
				if($group2['bidgroup_id']==$word['bidgroup_id']){
					
					$allWords[$wordKey]['groupInfo'] = $group2;
				}
			}
			
			
		}
		
		
		
		
		foreach($allWords as $wordKey=>$word){
			
			
		}
		
		
		
		AAA($allWords);
		
		
	}
	
	//根据K值获取APP信息
	public function getAppInfoByK(){
		
		$k     =  empty($_REQUEST['k2'])?'':$_REQUEST['k2'];
		
		$where = array();
		$where['identify'] = $k;
		
		$res = M('apps')->where($where)->find();
		
		
		$res['course'] = unserialize($res['course']);
		
		$return  = array();
		$return['status']    = 1;
		$return['data']      = $res;
		
		$this->returnData($return);
	}
	
	//更改是否第一次登陆状态
	public function updateFristStatus(){
		
		$k     =  empty($_REQUEST['k'])?'':$_REQUEST['k'];
		
		$member_id      = $this->member_id;
		$appInfo        = getAppInfoByK($k);
		
		$dataSave = array();
		$dataSave['member_id']            = $member_id;
		$dataSave[$appInfo['isFirstKey']] = 1;
		
		$res = M('member')->save($dataSave);
		
		$return  = array();
		$return['status']    = 0;
		
		if($res){
			$return['status']    = 1;
		}else{
			$return['status']    = 0;
		}
		
		$this->returnData($return);
	}
	
	//根据关键词获取出价记录
	public function getPreByWord(){
		
		$keyword_id     = empty($_REQUEST['keyword_id'])?0:$_REQUEST['keyword_id'];
		$member_id      = $this->member_id;
		
		$where = array();
		$where['keyword_id'] = $keyword_id;
		$where['member_id']  = $member_id;
	
		$list = M('precord')->where($where)->order('precord_id DESC')->limit(0,30)->select();
		
		$return  = array();
		$return['status']    = 1;
		$return['data']      = empty($list)?array():$list;
		
		$this->returnData($return);
	}
	
	//导出关键词记录
	public function wordExcelOut(){
		
		$member_id      = $this->member_id;
		$action         = empty($_REQUEST['action'])?'':$_REQUEST['action'];
		$bidgroup_id    = empty($_REQUEST['bidgroup_id'])?'':$_REQUEST['bidgroup_id'];
		$status         = empty($_REQUEST['status'])?'':$_REQUEST['status'];
		$title          = empty($_REQUEST['title'])?'':$_REQUEST['title'];
		$qs_star        = empty($_REQUEST['qs_star'])?'':$_REQUEST['qs_star'];
		
		$where   = array();
		$where['member_id'] = $member_id;
		$where['status']    = 0;
		
		$memberInfo     = M('member')->where($where)->find();
		
		$is_testMember  = false; 
		
		if(!empty($memberInfo)){
			
			$days   = intval(($memberInfo['endtime']-$memberInfo['addtime'])/86400);
			
			if($days<=20){
				
				$is_testMember = true;
				
				$export = $memberInfo['export'];
			
				if($export>=2){
					
					echo '当前购买套餐为试用版，导出限制次数为2次，当前已使用导出次数为2次，请购买一个月或以上的套餐享有无限制次数使用关键词导出功能！'; exit;
				}
			}
			
			
		}else{
			
			echo '';  exit;
		}
		
		$where  = '';
		$where  = 'member_id='.$member_id;
		
		
				
		if(!empty($bidgroup_id)){
			
			$bidgroupArr = explode('-',trim($bidgroup_id,'-'));
			
			$tempStr = '';
			foreach($bidgroupArr as $key=>$val){
				
				if($key==0){
					
					$tempStr.=' ( bidgroup_id='.$val;
				}else{
					$tempStr.=' OR bidgroup_id='.$val;
				}
				if($key==(count($bidgroupArr)-1)){
					
					$tempStr.=' ) ';
				}
			
			}
			$where.=' AND '.$tempStr;
			//$where.=' AND bidgroup_id='.$bidgroup_id;
		}
			
		
		if(!empty($status)){
			
			$where.=' AND status="'.$status.'"';
		}
		
		if(!empty($title)){
			
			$title = urldecode($title);
			
			$where.=' AND keyword like "%'.$title.'%"';
		}
		
		
		
		if(!empty($qs_star)){
			
			
			$qs_star = urldecode($qs_star);
			
			$qs_starArr = explode('-',trim($qs_star,'-'));
			$tempStr = '';
			
			foreach($qs_starArr as $key2=>$val){
				
				if($key2==0){
					$tempStr .= 'qs_star='.$val;
				}else{
					
					$tempStr .= ' OR qs_star='.$val;
				}
			}
			
			$tempStr = ' ( '.$tempStr.' )';
			
			$where .= ' AND '.$tempStr;
		}
		
		$wordsList = M('bidgroup_words')->where($where)->select();
		
		vendor('Form.Excel.PHPExcel');
		$objExcel  = new PHPExcel();
		$objWriter = new PHPExcel_Writer_Excel2007($objExcel); 
		$objProps = $objExcel->getProperties ();
		$objExcel->setActiveSheetIndex( 0 );
		$objActSheet = $objExcel->getActiveSheet ();
		
		$index = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');
		
		$objActSheet->getColumnDimension('A')->setWidth(45);
		$objActSheet->getColumnDimension('B')->setWidth(14);
		$objActSheet->getColumnDimension('C')->setWidth(14); 
		$objActSheet->getColumnDimension('D')->setWidth(14); 
		$objActSheet->getColumnDimension('E')->setWidth(14); 
		$objActSheet->getColumnDimension('F')->setWidth(14); 
		$objActSheet->getColumnDimension('G')->setWidth(14); 
		$objActSheet->getColumnDimension('H')->setWidth(14); 
		$objActSheet->getColumnDimension('I')->setWidth(14); 
		$objActSheet->getColumnDimension('J')->setWidth(14); 
		$objActSheet->getColumnDimension('K')->setWidth(14); 
		$objActSheet->getColumnDimension('L')->setWidth(14); 
		
		$objActSheet->setCellValueExplicit ( $index[0].(0+1),'关键词名称', PHPExcel_Cell_DataType::TYPE_STRING);
		$objActSheet->setCellValueExplicit ( $index[1].(0+1),'出价', PHPExcel_Cell_DataType::TYPE_STRING);
		$objActSheet->setCellValueExplicit ( $index[2].(0+1),'推广评分', PHPExcel_Cell_DataType::TYPE_STRING);
		$objActSheet->setCellValueExplicit ( $index[3].(0+1),'搜索热度', PHPExcel_Cell_DataType::TYPE_STRING);
		$objActSheet->setCellValueExplicit ( $index[4].(0+1),'购买竞争', PHPExcel_Cell_DataType::TYPE_STRING);
		$objActSheet->setCellValueExplicit ( $index[5].(0+1),'曝光量', PHPExcel_Cell_DataType::TYPE_STRING);
		$objActSheet->setCellValueExplicit ( $index[6].(0+1),'点击', PHPExcel_Cell_DataType::TYPE_STRING);
		$objActSheet->setCellValueExplicit ( $index[7].(0+1),'花费', PHPExcel_Cell_DataType::TYPE_STRING);
		$objActSheet->setCellValueExplicit ( $index[8].(0+1),'平均点击', PHPExcel_Cell_DataType::TYPE_STRING);
		$objActSheet->setCellValueExplicit ( $index[9].(0+1),'推广时长', PHPExcel_Cell_DataType::TYPE_STRING);
		$objActSheet->setCellValueExplicit ( $index[10].(0+1),'点击率', PHPExcel_Cell_DataType::TYPE_STRING);
		$objActSheet->setCellValueExplicit ( $index[11].(0+1),'推广产品', PHPExcel_Cell_DataType::TYPE_STRING);
		
		foreach($wordsList as $key=>$val){
			
			$objActSheet->setCellValueExplicit ( $index[0].($key+2),$val['keyword'], PHPExcel_Cell_DataType::TYPE_STRING);
			$objActSheet->setCellValueExplicit ( $index[1].($key+2),$val['price'],    PHPExcel_Cell_DataType::TYPE_STRING);
			$objActSheet->setCellValueExplicit ( $index[2].($key+2),$val['qs_star'],   PHPExcel_Cell_DataType::TYPE_STRING);
			$objActSheet->setCellValueExplicit ( $index[3].($key+2),$val['search_count'],    PHPExcel_Cell_DataType::TYPE_STRING);
			$objActSheet->setCellValueExplicit ( $index[4].($key+2),$val['buy_count'],    PHPExcel_Cell_DataType::TYPE_STRING);
			$objActSheet->setCellValueExplicit ( $index[5].($key+2),$val['impression_cnt'],    PHPExcel_Cell_DataType::TYPE_STRING);
			$objActSheet->setCellValueExplicit ( $index[6].($key+2),$val['click_cnt'],    PHPExcel_Cell_DataType::TYPE_STRING);
			$objActSheet->setCellValueExplicit ( $index[7].($key+2),$val['cost'],    PHPExcel_Cell_DataType::TYPE_STRING);
			$objActSheet->setCellValueExplicit ( $index[8].($key+2),$val['click_cost_avg'],    PHPExcel_Cell_DataType::TYPE_STRING);
			$objActSheet->setCellValueExplicit ( $index[9].($key+2),$val['online_time'],    PHPExcel_Cell_DataType::TYPE_STRING);
			$objActSheet->setCellValueExplicit ( $index[10].($key+2),$val['ctr'],    PHPExcel_Cell_DataType::TYPE_STRING);
			$objActSheet->setCellValueExplicit ( $index[11].($key+2),$val['match_count'],    PHPExcel_Cell_DataType::TYPE_STRING);
		}
		
		//执行excel生成
		$url = 'Admin/Runtime/Temp/excels/'.date('Y-m',time()).'/';
		if(!is_dir($url)){

			mkdir($url,0777,true);
		}

		
		$fileName = '关键词记录-('.date("Y年m月d日H时i分s秒").').xlsx';
		//AAA($fileName);
		$outputFileName = iconv ( 'UTF-8', 'gb2312', $url.$fileName );

		//直接导出文件

		$objWriter->save ( $outputFileName );
		
		$all = $url.$fileName;
		
		$dataSave = array();
		$dataSave['member_id'] = $member_id;
		$dataSave['export']    = $memberInfo['export'] + 1;
		M('member')->save($dataSave);
		
		downloads($all);
	}
	
	
	
	
	
	
	//根据阿里巴巴账号获取用户ID
	public function getMemId($username){
		
		$cond = array();
		$cond['username'] = $username;
		
		$userInfo = M('member')->where($cond)->find();
		
		if($userInfo){
			
			return $userInfo['member_id'];
		}else{
			
			return '0';
		}
	}
	
	
	//返回处理方法
	public function returnData($data){
		
		header("Access-Control-Allow-Origin: *");
		header("Content-type: text/html; charset=utf-8");
		echo json_encode($data);
		exit;
	}
	
	
	
	
}



?>